import sys
sys.path.append("..")  # 也可以这样
from config import kLocUserImagesPath, kUserSwapperFaceFrames, kSourceGIFFrame
from utils import gif_utils
from tybase.tools.image_utils import delete_file_or_directory
from tybase.tools.image_utils import url_to_md5
from utils.cloud_utils import upload_file_to_aliyun, transform_path, upload_file_to_qiniu
from utils import face_swapper_process
from loguru import logger
from utils.image_utils import process_user_image
import requests
import loguru
import time
import os



# from tybase.tools.video_utils import synthesize_video


def notify(task):
    url = "http://api.gpuhub.xiaolubi.com/task/queue/completion"  # 修改了gpu的地址
    headers = {
        "TOKEN": "inUVBuypkgdmm5ym6l3XiIMwenb7SKQu"
    }
    data = {
        "queue_id": task.id,
        "status": 100 if task.status == "completed" else 250,
        "error_message": ""
    }
    try:
        if not task.result:
            logger.error(f"task的result为空")
            data["convert_url"] = ""
            data["status"] = 250
            data["error_message"] = "其他错误"
        else:
            data["convert_url"] = task.result["ty_path"]
            if task.status == "failed":
                data["status"] = 250
            elif task.result["verify_face"] is False:
                data["status"] = 250
                data["error_message"] = task.result["error_message"]
            elif data["error_message"]:
                data["status"] = 250

    except Exception as e:
        data["convert_url"] = ""
        data["status"] = 250
        data["error_message"] = f"系统其他错误{str(e)[:200]}"
        import traceback
        traceback.print_exc()
        logger.error(f'Notify failed due to: {str(e)}')

    # 这里如果失败次数的多的话,可能会卡住
    for i in range(3):
        try:
            response = requests.post(url, json=data, headers=headers)
            logger.success(
                f"{data['convert_url']} -> {response.status_code} -> 通知成功!")
            logger.info(f"data: {data}")
            logger.info(f"result: {task.result}")
            break
        except:
            time.sleep(1)
            print("失败...开始尝试重新尝试..")
            continue

# 视频换脸流程

# 这可以传递一个人脸修复的参数
def GIF_换脸(gif_url, 用户图片url, 水印, oss_name="ali",GFPGANAmount=100):
    try:
        # 提取本地的用户图片的目录,( 把线上的图片先转换成本地的图片)
        loc_user_path_path = process_user_image(
            用户图片url, user_images_name=kLocUserImagesPath, max_dimension=350)
        # 这个逻辑基本是不变的
    except Exception as e:
        return {
            "video_loc_frame_path": gif_url,
            "loc_user_path_path": 用户图片url,
            "verify_face": False,
            "ty_path": "",
            "error_message": "下载用户图片失败"
        }
    # 检查本地 loc_user_path_path 是否存在,用os检查
    if not os.path.exists(loc_user_path_path):
        logger.error("用户图片不存在")

    # 这里先不做人脸验证,直接进行下一步

    # 提取本地的视频目录
    try:
        if 水印:
            watermark = {
                'text': "Generated by AI",
                'font_scale': 1/30,
                'position': 'bottom',
                'offset_ratio': 0.02,
                # Set transparency to be 64 (0 is fully transparent, 255 is fully opaque)
                'alpha': 190
            }
        else:
            watermark = None

        gif_handler = gif_utils.GifHandler(kSourceGIFFrame, watermark)
        # 本地的路径地址
        gif_file_dir,frame_delays = gif_handler.download_and_split_gif(
            gif_url)[1:]  # 下载了很多gif的图片,返回的是gif的框,但是也要返回文件夹
        loguru.logger.debug(f"gif_file_dir: {gif_file_dir}")

        # # 把这个地方改一下,,改成用其他接口的方式
        output_directory_name = face_swapper_process.process_images(loc_user_path_path, gif_file_dir,
                                                                    f"{gif_file_dir}_{int(time.time())}",
                                                                    GFPGANAmount
                                                                    )

        logger.info(f"git图片分割完成 -> {output_directory_name}")
        # 针对图片进行合成
        output_path = kUserSwapperFaceFrames + \
            f"/{url_to_md5(gif_url).split('.')[0]}_{int(time.time())}.gif"
        gif_handler.create_gif(frame_pattern='frame_', output_gif_path=output_path,
                               frame_dir=output_directory_name, frame_delays=frame_delays) # 这个duration需要单独传出来

        # if 水印:
        #     加水印(output_path, fontfile_path=kFontPath)

        aliyun_file_path = transform_path(output_path)

        # 把链接上传到阿里云,构建好完整的路径

        if oss_name == "qiniu":
            cloud_url = res_url = upload_file_to_qiniu(
                aliyun_file_path, output_path)
        else:
            cloud_url = upload_file_to_aliyun(
                aliyun_file_path, output_path)
            res_url = cloud_url.split('aliyuncs.com/')[-1]
        return {
            "video_loc_frame_path": gif_file_dir,
            "loc_user_path_path": loc_user_path_path,
            "output_directory_name": output_directory_name,
            "output_path": output_path,
            "aliyun_file_path": cloud_url,
            "ty_path": res_url,
            "verify_face": True,
            "error_message": ""
        }

    except Exception as e:
        logger.error(e)
        return {
            "video_loc_frame_path": gif_file_dir,
            "loc_user_path_path": loc_user_path_path,
            "output_directory_name": output_directory_name,
            "output_path": output_path,
            "aliyun_file_path": cloud_url,
            "ty_path": res_url,
            "verify_face": True,
            "error_message": e[:200]
        }
    finally:
        delete_file_or_directory(output_directory_name)
        delete_file_or_directory(output_path)
        delete_file_or_directory(loc_user_path_path)
        delete_file_or_directory(gif_file_dir)


if __name__ == '__main__':
    GIF = GIF_换脸(gif_url="https://ty-huanlian.oss-cn-shanghai.aliyuncs.com/test/yato-herzog.gi",
                 用户图片url="http://usfile.chaotuapp.com/upload/android/1691556085061/404543.jpg", 水印=True, oss_name="ali")
    print(GIF)
